// hostsDlg.cpp : implementation file
//

#include "stdafx.h"
#include "hosts.h"
#include "hostsDlg.h"
#include "ProcessThread.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CHostsDlg dialog

CHostsDlg::CHostsDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CHostsDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CHostsDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CHostsDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CHostsDlg)
	DDX_Control(pDX, IDC_NSLOOKUP, m_nslookup);
	DDX_Control(pDX, IDC_STATUS, m_status);
	DDX_Control(pDX, IDC_PROGRESS, m_progress);
	DDX_Control(pDX, IDC_OUTPUT, m_output);
	DDX_Control(pDX, IDC_INPUT, m_input);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CHostsDlg, CDialog)
	//{{AFX_MSG_MAP(CHostsDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_NSLOOKUP, OnNslookup)
	ON_WM_CLOSE()
	ON_WM_CHAR()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CHostsDlg message handlers

static const UINT BUFSZ = 512;
static const CString author = "@54c3\r\n";
static const CString config_file = "hosts.conf";

BOOL CHostsDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	
    
    CFile file(config_file, CFile::modeCreate | CFile::modeNoTruncate | CFile::modeRead);
    CString input;
    char buffer[BUFSZ];
    UINT len = -1;

    file.SeekToBegin();
    
    memset(buffer, 0, BUFSZ);
    len = file.Read(buffer, author.GetLength());
    if (author.Compare(buffer) != 0)
    {
        return TRUE;
    }

    while (len != 0)
    {
        memset(buffer, 0, BUFSZ);
        len = file.Read(buffer, BUFSZ - 1);
        input = input + buffer;
    }

    m_input.SetWindowText(input);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CHostsDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CHostsDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CHostsDlg::OnNslookup()
{
    AfxBeginThread((AFX_THREADPROC)workcallback, this);
}

CString CHostsDlg::GetHost( const CString& _hostname )
{
    CString ret;
    CString buf;
    CString hostname = _hostname;

    hostname.TrimLeft();
    hostname.TrimRight();
    if (hostname.IsEmpty())
    {
        return "\r\n";
    }

    if (hostname.GetAt(0) == '#')   // comment
    {
        return hostname + "\r\n";
    }

    struct hostent* host = gethostbyname(hostname);
    unsigned char split[4];
    unsigned long* x;
    bool multihost = false;
    bool beginalpha = false;
    
    if (host == NULL)
    {
        memset(split, 0, sizeof(split));
    }
    else
    {
        if (host->h_length > 1)
        {
            multihost = true;
        }
        x = (unsigned long*)&host->h_addr_list[0];
        for (; ; ++x)
        {
            if (!beginalpha)
            {
                if (*x == 0)
                {
                    beginalpha = true;
                    continue;
                }
                continue;
            }

            buf.Format("%s\t%s\r\n",
                inet_ntoa(*(in_addr*)x),
                hostname);

            ret += buf;
            if (x + 1 >= (unsigned long*)host->h_name)
            {
                break;
            }
        }
        if (multihost)
        {
            ret += "\r\n";
        }
    }


    return ret;
}

void CHostsDlg::OnClose() 
{
    CFile file(config_file, CFile::modeCreate | CFile::modeWrite);
    CString input;

    m_input.GetWindowText(input);

    file.Write(author, author.GetLength());
    file.Write(input, input.GetLength());

    file.Close();
	
	CDialog::OnClose();
}

void CHostsDlg::Run()
{
    CString input;
    CString output;
    CStringArray namearray;
    CString status;
    int count = 0;
    
    
    m_nslookup.ShowWindow(SW_HIDE);
    m_status.ShowWindow(SW_SHOW);
    
    status = "ready.";
    m_status.SetWindowText(status);
    
    m_input.GetWindowText(input);
    
    int len = 0;
    
    for (int i = 0; i != input.GetLength(); ++i)
    {
        ++len;
        if (input[i] == '\n')
        {
            namearray.Add(input.Mid(i - len, len));
            len = 0;
        }
        status.Format("%d line(s) processed.", namearray.GetSize());
        m_status.SetWindowText(status);
    }
    
    status.Format("okay, now begin to NsLookup.");
    m_status.SetWindowText(status);
    
    namearray.Add(input.Mid(i - len));
    
    count = namearray.GetSize();
    
    m_progress.SetRange(0, count);
    m_progress.SetPos(0);
    m_progress.ShowWindow(SW_SHOW);
    
    for (int j = 0; j != count; ++j)
    {
        status.Format("%s, %d/%d.", namearray[j], j + 1, count);
        m_status.SetWindowText(status);
        
        output += GetHost(namearray[j]);
        
        m_output.SetWindowText(output);
    }
        
    
    m_progress.ShowWindow(SW_HIDE);
    m_status.ShowWindow(SW_HIDE);
    m_nslookup.ShowWindow(SW_SHOW);

}

CHostsDlg::~CHostsDlg()
{
    // delete m_thread;
}



UINT * workcallback( LPVOID ptr )
{
    ((CHostsDlg*)ptr)->Run();

    return NULL;
}
